package com.example.multithread.chapter01;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName ConditionDemo
 * @Description TODO
 * @Author leejiliang
 * @DateTime 2020/5/11 2:05 PM
 * @Version 1.0
 */
public class ConditionDemo {

	private final static Logger Log = LoggerFactory.getLogger(ConditionDemo.class);
	public static void main(String[] args) throws InterruptedException {
		ReentrantLock reentrantLock = new ReentrantLock();
		Condition condition = reentrantLock.newCondition();
		new Thread(()->{
			try {
				reentrantLock.tryLock();
				Log.info("线程1加锁成功");
				Log.info("线程1执行condition.await,线程被挂起.");
				condition.await();
				Log.info("线程被唤醒成功.");
			} catch (InterruptedException e) {
				e.printStackTrace();
			}finally {
				reentrantLock.unlock();
				Log.info("线程1释放锁完成.");
			}
		}).start();
		Thread.sleep(1000);
		new Thread(()->{
			try {
				reentrantLock.tryLock();
				Log.info("线程2加锁成功");
				Log.info("线程2唤醒其他等待锁资源的线程");
				condition.signal();
			} finally {
				reentrantLock.unlock();
				Log.info("线程2释放锁完成.");
			}
		}).start();
	}
}
